package com.shujia.mapredue;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class Demo7Combiner {

    public static class CombinerMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {

            String line = value.toString();
            String clazz = line.split(",")[4];

            context.write(new Text(clazz), new IntWritable(1));

        }
    }


    public static class Combiner extends Reducer<Text, IntWritable, Text, IntWritable> {
        /**
         * Combiner: 在map执行完之后执行，在map端进行预聚合
         */
        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {

            int sum = 0;
            for (IntWritable value : values) {
                sum += value.get();
            }

            context.write(key, new IntWritable(sum));

        }
    }


    public static class CombinerReduce extends Reducer<Text, IntWritable, Text, NullWritable> {
        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {

            int sum = 0;
            for (IntWritable value : values) {
                sum += value.get();
            }
            String clazz = key.toString();

            String line = clazz + "," + sum;

            context.write(new Text(line), NullWritable.get());

        }
    }


    public static void main(String[] args) throws Exception {

        Job job = Job.getInstance();

        job.setJobName("combiner");

        job.setJarByClass(Demo7Combiner.class);

        //设置map端
        job.setMapperClass(CombinerMapper.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);


        //指定Combiner
        job.setCombinerClass(Combiner.class);


        //设置educe端
        job.setReducerClass(CombinerReduce.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(NullWritable.class);


        FileInputFormat.addInputPath(job, new Path("/data/student"));

        FileOutputFormat.setOutputPath(job, new Path("/data/clazz_num"));


        job.waitForCompletion(true);


    }
}
